package com.yogee.topseller;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.yogee.core.base.HttpView;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.loading.CustomProgressDialog;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.AppManager;
import com.yogee.core.utils.LogUtils;
import com.yogee.core.utils.SharedPreferencesUtils;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.activity.CheckPermissionsActivity;
import com.yogee.topseller.activity.DingyueListActivity;
import com.yogee.topseller.activity.FlashActivity;
import com.yogee.topseller.activity.FlashDetailsActivity;
import com.yogee.topseller.activity.SubscriptionActivity;
import com.yogee.topseller.activity.login.model.bean.InterestLabelBean;
import com.yogee.topseller.activity.my.MaintainLablesActivity;
import com.yogee.topseller.activity.my.MyCommissionActivity;
import com.yogee.topseller.activity.my.MyOrderActivity;
import com.yogee.topseller.activity.my.PersonalDataActivity;
import com.yogee.topseller.activity.persenter.LocationPImpl;
import com.yogee.topseller.activity.persenter.LocationPersenter;
import com.yogee.topseller.activity.view.LocationView;
import com.yogee.topseller.adapter.InterestLabelAdapter;
import com.yogee.topseller.adapter.RankingRvAdapter;
import com.yogee.topseller.application.TopellerApplication;
import com.yogee.topseller.bean.BroadsideBean;
import com.yogee.topseller.bean.FastQueryBean;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.fragment.CollectFragment;
import com.yogee.topseller.fragment.DingyueProductFragment;
import com.yogee.topseller.fragment.HomeFragment;
import com.yogee.topseller.fragment.MyFragment;
import com.yogee.topseller.fragment.ProductFragment;
import com.yogee.topseller.fragment.home.FlashFragment;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.GlideUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static android.R.id.content;

public class MainActivity extends CheckPermissionsActivity implements HttpView {
    public static TabHost tabHost;
    private FrameLayout fl_main;
    private FragmentManager fm;

    private long mExitTime;
    private View popBg;
    private PopupWindow popupWindow;
    private PopupWindow popupWindow_createss;
    private PopupWindow popupWindow_search;

    protected ImmersionBar mImmersionBar;
    public CustomProgressDialog pd = null;

    public void dimissPd(){
        if(pd!=null)
            pd.dismiss();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        setContentView(R.layout.activity_main);
        AppManager.addActivity(this);
        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        fl_main = (FrameLayout) findViewById(R.id.fl_main);
        popBg = findViewById(R.id.pop_bg);
        pd = CustomProgressDialog.createDialog(this);
//        initSystemBar(this);
        // 7.0系统沉浸式修改
//        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);   //去除半透明状态栏
        tabHost.setup();
        tabHost.getTabWidget().setDividerDrawable(null);
        initView();

        PgyUpdateManager.setIsForced(true); //设置是否强制更新。true为强制更新；false为不强制更新（默认值）。
//        PgyUpdateManager.register(this);
        // 自定义面板
        PgyUpdateManager.register(MainActivity.this,
                new UpdateManagerListener() {

                    @Override
                    public void onUpdateAvailable(final String result) {

                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);

                        View popupWindowView = LayoutInflater.from(TopellerApplication.app).inflate(R.layout.pop_udpatel, null);

                        popupWindow_createss = new PopupWindow(popupWindowView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                        popupWindow_createss.setOutsideTouchable(true);
                        // 更新内容
                        TextView tv_update_info = (TextView) popupWindowView.findViewById(R.id.tv_update_info);
                        tv_update_info.setText(appBean.getReleaseNote());
                        TextView btn_update = (TextView) popupWindowView.findViewById(R.id.btn_update);
                        TextView tv_version = (TextView) popupWindowView.findViewById(R.id.tv_version);
                        tv_version.setText("升级到版本:"+appBean.getVersionName());

//                        TextView btn_cancels = (TextView) popupWindowView.findViewById(R.id.btn_cancels);
//                        btn_cancels.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                popupWindow_createss.dismiss();
//                            }
//                        });
                        // 点击更新
                        btn_update.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                startDownloadTask(MainActivity.this,appBean.getDownloadURL());
                            }
                        });
                        popupWindow_createss.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                            }
                        });
                        //显示位置
                        popupWindow_createss.showAtLocation(popBg, Gravity.CENTER, 0, 0);

//                        new AlertDialog.Builder(MainActivity.this)
//                                .setTitle("更新")
//                                .setMessage("")
//                                .setNegativeButton(
//                                        "确定",
//                                        new DialogInterface.OnClickListener() {
//
//                                            @Override
//                                            public void onClick(DialogInterface dialog,int which) {
//                                                startDownloadTask(MainActivity.this,appBean.getDownloadURL());
//                                            }
//                                        }).show();
                    }

                    @Override
                    public void onNoUpdateAvailable() {
                    }
                });
    }

    private void initView() {

        String[] titles = {"首页", "产品","","订阅", "我的"};
        for (int i = 0; i < titles.length; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.tab_tabhost, null);
            ImageView iv = (ImageView) view.findViewById(R.id.tab_tabhost_iv);
            TextView tv = (TextView) view.findViewById(R.id.tab_tabhost_tv);
            tv.setText(titles[i]);
            switch (i) {
                case 0:
                    iv.setImageResource(R.drawable.tab_home);
                    TabHost.TabSpec home = tabHost.newTabSpec("home").setIndicator(view).setContent(R.id.tab_home_fl);
                    tabHost.addTab(home);
                    break;
                case 1:
                    iv.setImageResource(R.drawable.tab_product);
                    TabHost.TabSpec product = tabHost.newTabSpec("product").setIndicator(view).setContent(R.id.tab_product_fl);
                    tabHost.addTab(product);
                    break;
                case 2:
                    TabHost.TabSpec test = tabHost.newTabSpec("shansou").setIndicator(view).setContent(R.id.tab_shansou_fl);
                    tabHost.addTab(test);
                    break;
                case 3:
                    iv.setImageResource(R.drawable.tab_dingyue);// tab_dingyue
                    TabHost.TabSpec collect = tabHost.newTabSpec("collect").setIndicator(view).setContent(R.id.tab_collect_fl);
                    tabHost.addTab(collect);
                    break;
                case 4:
                    iv.setImageResource(R.drawable.tab_my);
                    TabHost.TabSpec my = tabHost.newTabSpec("my").setIndicator(view).setContent(R.id.tab_my_fl);
                    tabHost.addTab(my);
                    break;
            }
        }

        fm = getSupportFragmentManager();
        final FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.tab_home_fl, new HomeFragment());
        ft.add(R.id.tab_product_fl, new ProductFragment());
//        ft.replace(R.id.tab_shansou_fl, new FlashFragment());
        ft.add(R.id.tab_collect_fl, new DingyueProductFragment());
        ft.add(R.id.tab_my_fl, new MyFragment());
        ft.commit();

        tabHost.setCurrentTab(0);   //防止重复点击 产生错误
        tabHost.getTabWidget().getChildTabViewAt(2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!AppUtil.isExamined(MainActivity.this)){
//                    tabHost.setCurrentTab(shansou);
//                    ToastUtils.showToast(MainActivity.this,"点击了闪搜");
                }else{
                    Boolean flag = (Boolean) SharedPreferencesUtils.get(MainActivity.this,SharedPreferencesUtils.HAVE_FLASH,false);
                    if(flag){
                        startActivity(new Intent().setClass(MainActivity.this,FlashActivity.class));
                    }else{
                        showSsPop();
                    }
                }

            }
        });
//        tabHost.getTabWidget().getChildTabViewAt(3).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if(!AppUtil.isExamined(MainActivity.this)){
//                }else{
//                    startActivity(new Intent().setClass(MainActivity.this, DingyueListActivity.class));
//                }
//
//            }
//        });
        tabHost.getTabWidget().getChildTabViewAt(3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(AppUtil.isExamined(MainActivity.this)){
                    tabHost.setCurrentTab(3);
                }

            }
        });

        tabHost.getTabWidget().getChildTabViewAt(4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(AppUtil.isExamined(MainActivity.this)){
                    tabHost.setCurrentTab(4);
                }

            }
        });

        ImageView Img_shansou = (ImageView) findViewById(R.id.img_shansou);
        Img_shansou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!AppUtil.isExamined(MainActivity.this)){
//                    tabHost.setCurrentTab(shansou);
//                    ToastUtils.showToast(MainActivity.this,"点击了闪搜");
                }else{
                    Boolean flag = (Boolean) SharedPreferencesUtils.get(MainActivity.this,SharedPreferencesUtils.HAVE_FLASH,false);
                    if(flag){
                        startActivity(new Intent().setClass(MainActivity.this,FlashActivity.class));
                    }else{
                        showSsPop();
                    }
                }
            }
        });
    }


    public void showSsPop() {
        View popupWindowView = LayoutInflater.from(TopellerApplication.app).inflate(R.layout.pop_shansou, null);
        int width = 0;
        if (popupWindow_createss == null || !popupWindow_createss.isShowing())
            width = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth()*4/5;
        popupWindow_createss = new PopupWindow(popupWindowView, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow_createss.setOutsideTouchable(true);
        popupWindow_createss.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popBg.setVisibility(View.GONE);
            }
        });

        ImageView img_close_btn = (ImageView) popupWindowView.findViewById(R.id.img_close_btn);
        img_close_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow_createss.dismiss();
            }
        });
        TextView create_shansou_btn = (TextView) popupWindowView.findViewById(R.id.create_shansou_btn);
        create_shansou_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ToastUtils.showToast(MainActivity.this,"创建闪搜");
                popupWindow_createss.dismiss();
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, FlashDetailsActivity.class);
                startActivity(intent);
            }
        });
        popupWindow_createss.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow_createss.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popBg.setVisibility(View.GONE);
            }
        });


        //菜单背景色
//        ColorDrawable dw = new ColorDrawable(0xffffffff);
//        popupWindow_createss.setBackgroundDrawable(dw);
        //显示位置
        popupWindow_createss.showAtLocation(popBg, Gravity.CENTER, 0, 0);
        popBg.setVisibility(View.VISIBLE);
    }




    private InterestLabelAdapter mAdapter;
    public void showSearchPop(List<InterestLabelBean.ListBean> lableBeen) {
        View popupWindowView = LayoutInflater.from(TopellerApplication.app).inflate(R.layout.pop_search, null);
        int width = 0;
        if (popupWindow_search == null || !popupWindow_search.isShowing())
            width = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth()*4/5;
        popupWindow_search = new PopupWindow(popupWindowView, width, LinearLayout.LayoutParams.MATCH_PARENT, true);

        popupWindow_search.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popBg.setVisibility(View.GONE);
            }
        });
        RecyclerView lableRv = (RecyclerView) popupWindowView.findViewById(R.id.search_lable_rv);
        TextView reset = (TextView) popupWindowView.findViewById(R.id.search_lable_reset_tv);
        TextView sure = (TextView) popupWindowView.findViewById(R.id.search_lable_sure_tv);
        lableRv.setLayoutManager(new LinearLayoutManager(this));
        lableRv.setHasFixedSize(true);
        mAdapter = new InterestLabelAdapter(this);
        lableRv.setAdapter(mAdapter);
        mAdapter.addData(lableBeen);

        //动画效果
        popupWindow_search.setAnimationStyle(R.style.AnimationRightFade);
        popupWindow_search.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popBg.setVisibility(View.GONE);
            }
        });
        //菜单背景色
        ColorDrawable dw = new ColorDrawable(0xffffffff);
        popupWindow_search.setBackgroundDrawable(dw);
        //显示位置
        popupWindow_search.showAtLocation(popBg, Gravity.RIGHT, 0, 500);
        popBg.setVisibility(View.VISIBLE);
    }

    public void showPop(BroadsideBean bean) {
        final BroadsideBean broadsideBean = bean;
        View popupWindowView = LayoutInflater.from(TopellerApplication.app).inflate(R.layout.menu_pop, null);
        int width = 0;
        if (popupWindow == null || !popupWindow.isShowing())
            width = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth()*3/5;
        popupWindow = new PopupWindow(popupWindowView, width, LinearLayout.LayoutParams.MATCH_PARENT, true);

        TextView name = (TextView) popupWindowView.findViewById(R.id.menu_name_tv);
        TextView yj = (TextView) popupWindowView.findViewById(R.id.menu_yj_tv);
        TextView order = (TextView) popupWindowView.findViewById(R.id.menu_order_tv);
        ImageView photo = (ImageView) popupWindowView.findViewById(R.id.menu_photo_iv);
        LinearLayout tel = (LinearLayout) popupWindowView.findViewById(R.id.menu_tel_ll);
        RelativeLayout yjRl = (RelativeLayout) popupWindowView.findViewById(R.id.menu_yj_rl);
        RelativeLayout orderRl = (RelativeLayout) popupWindowView.findViewById(R.id.menu_order_rl);
        RelativeLayout ssRl = (RelativeLayout) popupWindowView.findViewById(R.id.menu_ss_rl);
        RelativeLayout rgRl = (RelativeLayout) popupWindowView.findViewById(R.id.menu_rg_rl);
        LinearLayout lablesLl = (LinearLayout) popupWindowView.findViewById(R.id.menu_lables_ll);
        LinearLayout lablesOutLl = (LinearLayout) popupWindowView.findViewById(R.id.menu_lables_out_ll);

        RelativeLayout menu_ss_labels = (RelativeLayout) popupWindowView.findViewById(R.id.menu_ss_labels);
        menu_ss_labels.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ToastUtils.showToast(MainActivity.this,"修改标签");
                startActivity(new Intent(MainActivity.this, MaintainLablesActivity.class));
            }
        });

        name.setText(bean.getName());
        yj.setText(bean.getCommmoney());
        order.setText("订单数：" + bean.getNum());
        GlideUtils.circleImage(this, bean.getUserImg(), photo);
        //标签
        for (int i = 0; i < bean.getLabel().size(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.menu_tv, null);
            TextView tv = (TextView) view.findViewById(R.id.menu_tv);
            tv.setText(bean.getLabel().get(i).getName());
            lablesLl.addView(view);
        }
        //标签
        lablesOutLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, MaintainLablesActivity.class));
//                popupWindow.dismiss();
            }
        });
        //头像
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, PersonalDataActivity.class));
                popupWindow.dismiss();
            }
        });
        //佣金
        yjRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, MyCommissionActivity.class));
//                popupWindow.dismiss();
            }
        });
        //订单
        orderRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, MyOrderActivity.class));
//                popupWindow.dismiss();
            }
        });
        //闪搜
        ssRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                popupWindow.dismiss();
//                HomeFragment.vpProductList.setCurrentItem(3);
                if(AppUtil.isExamine(MainActivity.this)){
                    startActivity(new Intent().setClass(MainActivity.this,FlashActivity.class));
                }
            }
        });
        //认购
        rgRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, SubscriptionActivity.class));
//                popupWindow.dismiss();
            }
        });
        //客服电话
        tel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try{
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + broadsideBean.getTel());
                    intent.setData(data);
                    startActivity(intent);
                }catch (Exception e){
                    ToastUtils.showToast(MainActivity.this,"您的手机暂时不支持此功能");
                }

            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popBg.setVisibility(View.GONE);
            }
        });

        //动画效果
        popupWindow.setAnimationStyle(R.style.AnimationRightFade);
        //菜单背景色
        ColorDrawable dw = new ColorDrawable(0xffffffff);
        popupWindow.setBackgroundDrawable(dw);
        //显示位置
        popupWindow.showAtLocation(popBg, Gravity.RIGHT, 0, 500);
        popBg.setVisibility(View.VISIBLE);
    }

    public static void initSystemBar(Activity activity) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            setTranslucentStatus(activity, true);

        }
        SystemBarTintManager tintManager = new SystemBarTintManager(activity);

        tintManager.setStatusBarTintEnabled(true);
//        tintManager.setNavigationBarTintEnabled(true);//开启导航栏着色
//        tintManager.setStatusBarAlpha(0.0f);
        tintManager.setStatusBarTintResource(R.drawable.background_title_bg_all);

    }

    @TargetApi(19)
    private static void setTranslucentStatus(Activity activity, boolean on) {

        Window win = activity.getWindow();

        WindowManager.LayoutParams winParams = win.getAttributes();

        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;

        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void loadingFinished() {

    }

    @Override
    public void showMsg(String msg) {

    }

    @Override
    public <T> LifecycleTransformer<T> bindRecycler() {
        return null;
    }


    private void fastQuery(String userId) {
//        if(queryList!=null&&queryList.size()>0){
//            startActivity(new Intent().setClass(MainActivity.this,FlashActivity.class));
//        }else{
//            showSsPop();
//        }

    }
}